<template>
	<view class="addProduct" @click="nameListStatus=false">
		<nav-bar :title="status?'商品编辑':'新增商品'"></nav-bar>
		<view class="search-box">
			<view class="picker">
				<view v-for="(item,index) in PickerList" :class="item.label?'':'select'" :key="index"
					@click.stop="openShow(item)">
					<text>{{item.label||item.acquiesce}}</text>
				</view>
			</view>
			<u-picker :show="PickerList[0].show" :columns="columns[0]" keyName="deptName" @confirm="confirm1"
				@cancel='PickerList[0].show = false'></u-picker>
			<u-picker :show="PickerList[1].show" :columns="columns[1]" keyName="deptName" @confirm="confirm2"
				@cancel='PickerList[1].show = false'></u-picker>
			<u-picker :show="PickerList[2].show" :columns="columns[2]" keyName="deptName" @confirm="confirm3"
				@cancel='PickerList[2].show = false'></u-picker>
		</view>
		<scroll-view class="form-box" scroll-y :style="{'height': `calc(${scrollHeight} - 214rpx)`}">
			<uni-forms ref="form">
				<uni-forms-item label="名称" class="form-items" name="" required>
					<input type="text" placeholder="请输入名称" @click.stop="nameListStatus=true" @input="iptName"
						v-model="formData.goodName" />
					<view class="iptIcon" @click.stop="openNameList">
						<image v-if="!nameListStatus" src="/static/images/issue_off.png" mode="widthFix"></image>
						<image v-else src="/static/images/issue_open.png" mode="widthFix"></image>
					</view>
					<scroll-view scroll-y class="iptList" v-if="nameListStatus">
						<view v-for="option in iptNameList" :key="option.id" @click.stop="selectOption(option)">
							{{ option.goodName }}
						</view>
						<text v-if="iptNameList.length<=0" style="display: block;text-align: center;">暂无数据</text>
					</scroll-view>
				</uni-forms-item>
				<uni-forms-item v-if="roleId===3" label="区域选择" class="form-items" name="" required>
					<!-- <u-select v-model="selectedItems" @change="handleChange">
						<u-option v-for="(item,index) in options" :value="item.value"
							:key="index">{{item.text}}</u-option>
					</u-select> -->
					<select-cy multiple :value="selectedItems" :options="options" @change="handleChange"></select-cy>
				</uni-forms-item>
				<uni-forms-item label="商品图片" class="form-items picture" name="">
					<view style="width: 30%;padding: 10upx 0;">
						<uni-file-picker v-model="Images" :limit="1" :imageStyles="imageStyles"
							@select="uploadSelectStoreId($event)">
							<uni-icons type="camera-filled" size="30" color="#999999"></uni-icons>
							<view class="desc">点击上传</view>
						</uni-file-picker>
					</view>
				</uni-forms-item>
				<uni-forms-item label="详情图片" class="form-items picture" name="">
					<view style="padding: 10upx 0;">
						<uni-file-picker v-model="Images2" :limit="10" :imageStyles="imageStyles"
							@select="uploadSelectStoreId2($event)" @delete="delete2">
							<uni-icons type="camera-filled" size="30" color="#999999"></uni-icons>
							<view class="desc">点击上传</view>
						</uni-file-picker>
					</view>
				</uni-forms-item>
				<uni-forms-item label="详情介绍" class="form-items" name="">
					<u-textarea style="background-color: #f5f5f5;" v-model="formData.goodText"
						placeholder="详情介绍"></u-textarea>
				</uni-forms-item>
				<uni-forms-item label="库存" class="form-items" name="retail" required>
					<input type="text" placeholder="请输入库存" v-model.number="formData.counts" />
				</uni-forms-item>
				<uni-forms-item label="零售价" class="form-items" name="retail" required>
					<input type="text" placeholder="请输入零售价" v-model.number="formData.retailPrice" />
				</uni-forms-item>
				<uni-forms-item label="批发价" class="form-items" name="wholesale" required>
					<input type="text" placeholder="请输入批发价" v-model.number="formData.tradePrice" />
				</uni-forms-item>
			</uni-forms>
		</scroll-view>
		<you-bottom-btn :btnConfig="bottomBtnConfig" @clickSubmit="clickSubmit"></you-bottom-btn>
	</view>
</template>

<script>
	import {
		baseUrl,
		baseIconUrl,
		baseImgUrl
	} from '@/config'
	import {
		getMiniprogramToken
	} from "@/utils/auth"
	export default {
		data() {
			return {
				scrollHeight: '',
				status: false,
				baseUrl,
				baseIconUrl,
				baseImgUrl,
				Images: [],
				Images2: [],
				bottomBtnConfig: [{
					text: '提交审核',
					class: 'confirm',
					funcName: 'clickSubmit'
				}],
				exclude: [],
				PickerList: [{
						label: '全部',
						id: null,
						acquiesce: '全部',
						show: false
					},
					{
						label: null,
						id: null,
						acquiesce: '二级分类',
						show: false
					},
					{
						label: null,
						id: null,
						acquiesce: '三级分类',
						show: false
					},
				],
				columns: [
					[
						[{
							deptName: "全部",
							id: 1,
						}]
					],
					[
						[]
					],
					[
						[]
					]
				],
				imageStyles: {
					width: 100,
					height: 100,
					border: {
						color: "#D8DCE5",
						width: '2rpx',
						style: 'dashed',
						radius: '16rpx'
					}
				},
				formData: {
					goodName: '',
					goodImg: '',
					retailPrice: '',
					tradePrice: '',
					counts: '',
					goodDetail: [], //详情图片
					goodText: '', //详情介绍
				},
				detailImg: [],
				formSort: {
					classOneId: null, //一级分类
					classOneName: null, //一级分类名
					classTwoId: null, //二级分类
					classTwoName: null, //二级分类名
					classThreeId: null, //三级分类
					classThreeName: null //三级分类名
				},
				//区域
				selectedItems: [],
				options: [],
				ids: [],
				roleId: '',
				iptNameList: [],
				nameListStatus: false,
				iptNameOptions: []
			}
		},
		methods: {
			handleChange(e, r) {
				this.ids = []
				e.forEach((el) => {
					this.ids.push(el.id)
				})
				console.log('选择', this.ids);
			},
			async clickSubmit(item) {
				let data = {
					...this.formData,
					...this.formSort,
					goodImg: this.formData.goodImg,
					goodDetail: this.detailImg.toString()
				}
				if (data.classThreeId !== null && this.formData.goodName != '' && this.formData.goodName != null &&
					!isNaN(data.retailPrice) && this.formData.retailPrice != '' && this.formData.retailPrice != null &&
					!isNaN(data.tradePrice) && this.formData.tradePrice != '' &&
					this.formData.tradePrice != null && this.formData.counts != '' && this.formData.counts != null &&
					this.formData.retailPrice > 0) {
					const res = await this.$GET('/fx/user/getInfo')
					if (res.data.roleType === 4) {
						console.log(data);
						if (this.status) {
							const res4 = await this.$PUT(`/fx/store/good`, data)
							console.log(res4);
							uni.showToast({
								icon: 'success',
								title: `${res4.msg}`,
								duration: 2000
							})
							if (res4.code === 200) {
								setTimeout(() => {
									uni.navigateBack()
								}, 2000)
							}
						} else {
							const res4 = await this.$POST(`/fx/store/good/addGood`, data)
							console.log(res4);
							uni.showToast({
								icon: 'success',
								title: `${res4.msg}`,
								duration: 2000
							})
							if (res4.code === 200) {
								setTimeout(() => {
									uni.navigateBack()
								}, 2000)
							}
						}
					} else if (res.data.roleType === 3) {
						let data3 = {
							...data,
							region: this.ids.toString(),
							regionArr: this.ids
						}
						if (this.ids.length > 0) {
							const res4 = await this.$POST(`/fx/supplier/good`, data3)
							uni.showToast({
								icon: 'success',
								title: `${res4.msg}`,
								duration: 2000
							})
							if (res4.code === 200) {
								setTimeout(() => {
									uni.navigateBack()
								}, 2000)
							}
						} else {
							uni.showToast({
								icon: 'none',
								title: '请选择区域'
							})
						}
					}
				} else if (data.classThreeId == null) {
					uni.showToast({
						icon: 'none',
						title: '请把分类选择完整'
					})
				} else if (this.formData.goodName == '' || this.formData.goodName == null) {
					uni.showToast({
						icon: 'none',
						title: '请输入商品名称'
					})
				} else if (this.formData.counts != '' && this.formData.counts != null) {
					uni.showToast({
						icon: 'none',
						title: '请填写库存数量'
					})
				} else if (this.formData.retailPrice <= 0) {
					uni.showToast({
						icon: 'none',
						title: '库存数量不能小于1'
					})
				} else if (this.formData.retailPrice == '' || this.formData.retailPrice == null) {
					uni.showToast({
						icon: 'none',
						title: '请填写零售价'
					})
				} else if (isNaN(data.retailPrice)) {
					uni.showToast({
						icon: 'none',
						title: '请正确填写零售价'
					})
				} else if (this.formData.tradePrice == '' || this.formData.tradePrice == null) {
					uni.showToast({
						icon: 'none',
						title: '请填写批发价'
					})
				} else if (isNaN(data.tradePrice)) {
					uni.showToast({
						icon: 'none',
						title: '请正确填写批发价'
					})
				}
			},
			openShow(item) {
				this.PickerList.forEach((t) => {
					t.show = false
				})
				if (this.columns[0][0].length > 0 && item.acquiesce === this.PickerList[0].acquiesce) {
					this.PickerList[0].show = true
				}
				if (this.columns[1][0].length > 0 && item.acquiesce === this.PickerList[1].acquiesce) {
					this.PickerList[1].show = true
				}
				if (this.columns[2][0].length > 0 && item.acquiesce === this.PickerList[2].acquiesce) {
					this.PickerList[2].show = true
				}
				if (this.columns[2][0].length <= 0 && item.acquiesce === this.PickerList[2].acquiesce || this.columns[1][0]
					.length <= 0 && item.acquiesce === this.PickerList[1].acquiesce) {
					uni.showToast({
						icon: 'none',
						title: '目前没有更多分类了'
					})
				}
			},
			confirm1(e) {
				this.PickerList[0].label = e.value[0].deptName
				this.PickerList[0].id = e.value[0].id
				this.PickerList.forEach((t) => {
					t.show = false
				})
				this.columns[1][0] = []
				this.PickerList[1].label = null
				this.columns[2][0] = []
				this.PickerList[2].label = null
				// this.formSort.classOneId = e.value[0].id //一级分类
				// this.formSort.classOneName = e.value[0].deptName //一级分类名

			},
			confirm2(e) {
				if (this.PickerList[0].id) {
					this.PickerList[1].label = e.value[0].deptName
					this.PickerList[1].id = e.value[0].id
				}
				this.PickerList.forEach((t) => {
					t.show = false
				})
				this.columns[2][0] = []
				this.PickerList[2].label = null
				// this.formSort.classTwoId = e.value[0].id //二级分类
				// this.formSort.classTwoName = e.value[0].deptName //二级分类名
			},
			async confirm3(e) {
				this.formData = {}
				this.Images = []
				this.Images2 = []
				if (this.PickerList[1].id) {
					this.PickerList[2].label = e.value[0].deptName
					this.PickerList[2].id = e.value[0].id
					// const res = await this.$GET(`/fx/model/queryModelName?tierVal=${e.value[0].id}`)
					const res = await this.$GET(`/fx/model/hierarchy?hierarchy=${e.value[0].id}`)
					this.formData.goodName = res.data.goodName
					this.Images.push({
						url: this.baseUrl + res.data.goodImg
					})
					this.iptNameOptions = res.data.modelList
					this.iptNameList = this.iptNameOptions
				}
				this.PickerList.forEach((t) => {
					t.show = false
				})
				// this.formSort.classThreeId = e.value[0].id //三级分类
				// this.formSort.classThreeName = e.value[0].deptName //三级分类名
			},
			iptName(e) {
				this.nameListStatus = true
				this.formData = {}
				// this.Images = []
				this.Images2 = []
				this.formData.goodName = e.detail.value
				console.log(this.formData.goodName, e.detail.value);
				const query = this.formData.goodName.toLowerCase();
				this.iptNameList = this.iptNameOptions.filter(option =>
					option.goodName.toLowerCase().includes(query)
				);

			},
			selectOption(option) {
				this.formData.goodName = option.goodName
				this.formData = {}
				this.formData = {
					...option
				}
				this.Images = []
				if (option.goodImg !== null) {
					this.Images.push({
						url: this.baseUrl + option.goodImg
					})
					console.log(this.Images);
				}
				this.Images2 = []
				if (option.goodDetail !== null) {
					this.detailImg = option.goodDetail.split(',')
					option.goodDetail.split(',').forEach((el) => {
						this.Images2.push({
							url: this.baseUrl + el
						})
					})
					console.log(this.Image2);
				}
				this.nameListStatus = false
				// 这里可以处理选中的选项
			},
			openNameList() {
				this.nameListStatus = !this.nameListStatus
			},
			async uploadSelectStoreId(e) {
				const tempFilePaths = e.tempFilePaths
				const tempFiles = e.tempFiles[0]
				uni.uploadFile({
					url: this.baseUrl + '/common/upload',
					// H5上传
					// file: tempFilePaths,
					// 微信小程序上传
					filePath: tempFilePaths[0],
					name: 'file',
					header: {
						"Authorization": 'Bearer ' + getMiniprogramToken()
					},
					// 成功函数
					success: (res) => {
						// 取到文档服务器的值
						let uploadData = JSON.parse(res.data)
						console.log('上传成功的图片', uploadData)
						this.formData.goodImg = `${uploadData.fileName}`
						console.log(this.Images);
					},
					// 失败提示用户重新上传
					fail: error => {
						console.log('失败', error)
					}
				})
			},
			async uploadSelectStoreId2(e) {
				const tempFilePaths = e.tempFilePaths
				if (!tempFilePaths.length) return; //如果没有选择图片就退出
				//循环选择图片的张数
				tempFilePaths.map(async () => {
					const path = tempFilePaths.pop();
					//因为我这个后台给的接口一次只能上传一张图片，所以每循环一次就调用接口上传一次
					const [err, {
						data
					}] = await uni.uploadFile({
						url: this.baseUrl + '/common/upload', //后台地址
						filePath: path,
						name: 'file',
						header: {
							"Authorization": 'Bearer ' + getMiniprogramToken()
						},
					});
					//因为async返回的是个promise对象，所以要把返回的数据转为对象格式。
					let dataObj = JSON.parse(data)
					//每循环一次就把后台返回的图片地址添加到filePathsList数组
					this.detailImg.push(dataObj.fileName)
					console.log(this.detailImg);
				})
				// const tempFiles = e.tempFiles[0]
				// uni.uploadFile({
				// 	url: this.baseUrl + '/common/upload',
				// 	// H5上传
				// 	// file: tempFilePaths,
				// 	// 微信小程序上传
				// 	filePath: tempFilePaths[0],
				// 	name: 'file',
				// 	header: {
				// 		"Authorization": 'Bearer ' + getMiniprogramToken()
				// 	},
				// 	// 成功函数
				// 	success: (res) => {
				// 		// 取到文档服务器的值
				// 		let uploadData = JSON.parse(res.data)
				// 		console.log('上传成功的图片', uploadData)
				// 		this.detailImg.push(uploadData.fileName)
				// 		console.log(this.detailImg);
				// 	},
				// 	// 失败提示用户重新上传
				// 	fail: error => {
				// 		console.log('失败', error)
				// 	}
				// })
			},
			delete2(e, i) {
				this.detailImg.splice(i, 1);
				console.log(this.detailImg);
			}
		},
		watch: {
			PickerList: {
				handler: function(val, oldVal) {
					this.formSort.classOneId = val[0].id //一级分类
					this.formSort.classOneName = val[0].label //一级分类名
					this.formSort.classTwoId = val[1].id //二级分类
					this.formSort.classTwoName = val[1].label //二级分类名
					this.formSort.classThreeId = val[2].id //三级分类
					this.formSort.classThreeName = val[2].label //三级分类名
					console.log(this.formSort);
					this.exclude.forEach((t, i) => {
						if (t.ancestors === `0,${val[0].id}`) {
							this.columns[1][0].push(t)
						}
						if (t.ancestors === `0,${val[0].id},${val[1].id}`) {
							this.columns[2][0].push(t)
						}
					})
				},
				deep: true
			},
		},
		async onLoad(data) {
			this.iptNameList = this.iptNameOptions;
			this.scrollHeight = this.$store.getters.heightData.noTabMainHeight + 'px'
			this.roleId = uni.getStorageSync('roleId')
			if (data.status) {
				this.status = data.status
				let res = await this.$GET(`/fx/store/good/${data.id}`)
				this.formData = res.data
				if (res.data.goodImg !== null) {
					this.Images = []
					this.Images.push({
						url: this.baseUrl + res.data.goodImg
					})
					console.log(this.Images);
				}
				if (res.data.goodDetail !== null) {
					this.Images2 = []
					this.detailImg = res.data.goodDetail.split(',')
					res.data.goodDetail.split(',').forEach((el) => {
						this.Images2.push({
							url: this.baseUrl + el
						})
					})
					console.log(this.Image2);
				}
				this.PickerList[0].id = res.data.classOneId
				this.PickerList[0].label = res.data.classOneName
				this.PickerList[1].id = res.data.classTwoId
				this.PickerList[1].label = res.data.classTwoName
				this.PickerList[2].id = res.data.classThreeId
				this.PickerList[2].label = res.data.classThreeName
				console.log(res);
			}
			const res = await this.$GET(`/fx/goodclassify/list/exclude/${1}`)
			this.exclude = res.data
			this.exclude.forEach((t, i) => {
				if (t.ancestors === '0') {
					this.columns[0][0].push(t)
				}
			})

			let resOptions = await this.$GET(`/fx/goodarea/list?pageNum=1&pageSize=100`)
			this.options = resOptions.rows
		}
	}
</script>

<style lang="scss" scoped>
	.form-box {
		height: calc(100vh - 334upx);
	}

	.addProduct {
		min-height: 100vh;
		background: #ffffff;

		.search-box {
			background: #ffffff;

			.picker {
				display: flex;
				justify-content: space-between;
				margin: 20upx 34upx 6upx;

				>view {
					width: 30%;
					padding: 14upx 20upx;
					background: #f5f5f5;
					border-radius: 200upx;
					font-size: 24upx;
					text-align: center;
					box-sizing: border-box;
					position: relative;

					&::after {
						content: '*';
						color: red;
						position: absolute;
						left: -16upx;
						top: 0;
						font-size: 30upx;
					}
				}

				.select {
					color: #c7c7c7;
				}
			}
		}

		.form-box {}
	}
</style>
<style lang="scss">
	.uni-forms {
		padding: 20upx;

		.uni-forms-item {
			position: relative;
		}
	}

	.uni-forms-item {
		min-height: 100upx;
		align-items: center;
		margin: 0 !important;
		display: flex;
		flex-direction: column !important;
		align-content: flex-start;
	}

	.uni-forms-item__content {
		position: relative;

		input {
			display: block;
			height: 100%;
		}

		.iptIcon {
			position: absolute;
			right: 0;
			top: calc(100% - 60rpx);
			width: 60rpx;
			height: 60rpx;
			z-index: 1000;

			image {
				width: 100%;
				height: 60rpx;
			}
		}

		.iptList {
			position: absolute;
			width: 100%;
			left: 0;
			top: 70rpx;
			background: #f5f5f5;
			border-radius: 20rpx;
			padding: 10rpx;
			z-index: 1000;
			max-height: 300rpx;

			view {
				margin: 10rpx 0;
			}
		}

		.u-textarea {
			background: #f5f5f5 !important;
		}
	}

	.uni-forms-item__label {
		height: 100% !important;
		width: 100vw !important;
		font-size: 30upx !important;
		font-weight: 600;
		color: black !important;
		padding: 10upx 20upx !important;
	}

	.uni-forms-item__content {
		padding: 10upx;
		width: 100% !important;
		text-align: left !important;
		background: #f5f5f5;
		border-radius: 10upx;
	}

	.uni-forms-item {

		&:nth-of-type(2),
		&:nth-of-type(3),
		&:nth-of-type(4) {
			.uni-forms-item__content {
				background: #ffffff !important;
			}
		}

	}

	.is-required {
		position: absolute;
		left: -12upx;
	}
</style>